﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoMapper;
using Cari.IBP.Platform.Sidecar;
using CCcteg.Common;
using Ccteg.Common;
using Ccteg.DB;
using LinqKit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Cctegaq.Api.Controllers.Api
{
    /// <summary>
    /// 现场监管
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]

    public class RSSController : IbpControllerBase
    {
        private readonly IMapper _mapper;
        private readonly MySqlDbContext _dbContext;


        public RSSController(MySqlDbContext dbContext, IMapper mapper)
        {

            _dbContext = dbContext;
            _mapper = mapper;
        }
        #region 现场监管
        /// <summary>
        /// 现场监管 添加 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        
        public ResponseModel RSSAddOrUpdate([FromBody] Rss_Check_ViewModel model)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    var entity = _mapper.Map<Rss_Check_ViewModel, Rss_Check>(model);
                    var entryEntity = _dbContext.Rss_Check.Attach(entity);
                    if (entity.Id > 0)
                    {
                        var editentity = _dbContext.Rss_Check.AsNoTracking().Where(x => x.Id == entity.Id).AsNoTracking().FirstOrDefault();
                        if (editentity == null)
                        {
                            response.SetFailed("无法修改，数据不存在请刷新页面");
                            return response;
                        }
                        //要修改的类型
                        _dbContext.ModifyEntityValue(entity, x => new
                        {
                            x.CompanyNo,
                            x.CompanyName,
                            x.CompanyFullName,
                            x.SrbName,
                            x.Trade,
                            x.Category,
                            x.Leader,
                            x.PartMan,
                            x.CheckContent,
                            x.CheckDate
                        });
                        entity.ModifiedBy = "系统";
                        entity.ModifiedOn = System.DateTime.Now;
                        entity.State = "未检查";
                        entity.Leader = model.LeaderPart?.CheckMan;

                        _dbContext.Rss_Checkman.Where(x => x.CheckNo == entity.CheckNo && x.Deleted == false)
                        .SetField(x => x.Deleted).WithValue(true)
                        .SetField(x => x.ModifiedOn).WithValue(DateTime.Now)
                        .SetField(x => x.ModifiedBy).WithValue("系统")
                        .Update();
                        _dbContext.Rss_Checkman.Add(new Rss_Checkman()
                        {
                            CheckNo = entity.CheckNo,
                            CheckMan = model.LeaderPart?.CheckMan,
                            CheckManId = model.LeaderPart?.CheckManId,
                            LeadFlag = "1",
                            InOutFlag = "1",
                            CreatedBy = "系统",
                            CreatedOn = System.DateTime.Now
                        });
                        if (model.PartManList != null)
                        {

                            entity.PartMan = string.Join(",", model.PartManList.Select(x => x.CheckMan));
                            foreach (Rss_PartMan rss_PartMan in model.PartManList)
                            {
                                _dbContext.Rss_Checkman.Add(new Rss_Checkman()
                                {
                                    CheckNo = entity.CheckNo,
                                    CheckMan = rss_PartMan.CheckMan,
                                    CheckManId = rss_PartMan.CheckManId,
                                    LeadFlag = "0",
                                    InOutFlag = rss_PartMan.CheckManId == "" ? "0" : "1",
                                    CreatedOn = DateTime.Now,
                                    CreatedBy = "系统"
                                });
                            }
                        }
                    }
                    else
                    {
                        entryEntity.Property(p => p.ModifiedBy).IsModified = false;
                        entryEntity.Property(p => p.ModifiedOn).IsModified = false;
                        entity.Deleted = false;
                        entity.CreatedBy = "系统";
                        entity.CreatedOn = System.DateTime.Now;
                        entity.CompanyName = " 中国煤科";
                        entity.CompanyFullName = "中国煤科";
                        entity.CompanyNo = "001";
                        string checkno = DateTime.Now.ToFileTimeUtc().ToString();
                        entity.CheckNo = checkno;
                        entity.Leader = model.LeaderPart?.CheckMan;

                        _dbContext.Rss_Checkman.Add(new Rss_Checkman()
                        {
                            CheckNo = checkno,
                            CheckMan = model.LeaderPart?.CheckMan,
                            CheckManId = model.LeaderPart?.CheckManId,
                            LeadFlag = "1",
                            InOutFlag = "1",
                            CreatedBy = "系统",
                            CreatedOn = System.DateTime.Now,
                            Deleted = false
                        });
                        if (model.PartManList != null)
                        {
                            entity.PartMan = string.Join(",", model.PartManList.Select(x => x.CheckMan));
                            foreach (Rss_PartMan rss_PartMan in model.PartManList)
                            {
                                _dbContext.Rss_Checkman.Add(new Rss_Checkman()
                                {
                                    CheckNo = checkno,
                                    CheckMan = rss_PartMan.CheckMan,
                                    CheckManId = rss_PartMan.CheckManId,
                                    LeadFlag = "0",
                                    InOutFlag = rss_PartMan.CheckManId == "" ? "0" : "1",
                                    CreatedOn = DateTime.Now,
                                    CreatedBy = "系统",
                                    Deleted = false
                                });
                            }
                        }
                    }
                    _dbContext.SaveChanges();
                    response.SetSuccess("操作成功");

                }
            }
            catch (Exception ex)
            {
                response.SetFailed("操作失败");
                response.Data = ex.Message;
            }
            return response;
        }


        /// <summary>
        /// 现场监管 删除
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpPost]
      
        public ResponseModel RSSDelete([Required] int id)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    var query = _dbContext.Rss_Check.Where(x => x.Id == id);
                    var res = query
                        .SetField(x => x.Deleted).WithValue(true)
                        .SetField(x => x.ModifiedOn).WithValue(DateTime.Now)
                        .SetField(x => x.ModifiedBy).WithValue("系统")
                        .Update();
                    string checkno = query.FirstOrDefault()?.CheckNo;
                    _dbContext.Rss_Checkman.Where(x => x.CheckNo == checkno)
                        .SetField(x => x.Deleted).WithValue(true)
                        .SetField(x => x.ModifiedOn).WithValue(DateTime.Now)
                        .SetField(x => x.ModifiedBy).WithValue("系统")
                        .Update();
                    if (res > 0)
                        response.SetSuccess("删除成功");
                    else
                        response.SetFailed("删除失败");
                }
            }
            catch (Exception ex)
            {
                response.SetFailed("删除失败");
                response.Data = ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 现场监管 详情
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet]
        
        public ResponseModel<Rss_Check_ViewModel> RSSDetail([Required] int id)
        {
            using (_dbContext)
            {
                var response = new ResponseModel<Rss_Check_ViewModel>();
                var query = _dbContext.Rss_Check.AsNoTracking().Where(x => x.Id == id).FirstOrDefault();
                var data = _mapper.Map<Rss_Check, Rss_Check_ViewModel>(query);

                string checkno = query?.CheckNo;
                if (data != null)
                {
                    var leader = _dbContext.Rss_Checkman.AsNoTracking().Where(x => x.CheckNo == checkno && x.LeadFlag == "1" && x.Deleted == false).FirstOrDefault();
                    data.LeaderPart = new Rss_PartMan() { CheckManId = leader?.CheckManId, CheckMan = leader?.CheckManId };
                    var partman = _dbContext.Rss_Checkman.AsNoTracking().Where(x => x.CheckNo == checkno && x.LeadFlag == "0" && x.Deleted == false).ToList();
                    data.PartManList = new List<Rss_PartMan>();
                    foreach (Rss_Checkman rss_Part in partman)
                    {
                        data.PartManList.Add(new Rss_PartMan() { CheckManId = rss_Part.CheckManId, CheckMan = rss_Part.CheckMan });
                    }
                }
                response.SetData(data);
                return response;
            }
        }

        /// <summary>
        /// 现场监管查询
        /// </summary>
        /// <param name="companyno">受检单位</param>
        /// <param name="leader">带队检查人</param>
        /// <param name="partMan">参与人</param>
        /// <param name="checkdatestart">检查开始时间</param>
        /// <param name="checkdateend">检查结束时间</param>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">显示条数</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseResultModel<IEnumerable<Rss_Check_ViewModel>> RssRssSearch(string companyno, string leader, string partMan, DateTime? checkdatestart, DateTime? checkdateend, int pageindex = 1, int pagesize = 10)
        {
            using (_dbContext)
            {

                var response = ResponseModelFactory<IEnumerable<Rss_Check_ViewModel>>.CreateResultInstance;
                Expression<Func<Rss_Check, bool>> where = p => true;


                where = where.CheckNullAnd(x => x.CompanyNo == companyno, companyno);
                where = where.CheckNullAnd(x => x.Leader.Contains(leader), leader);
                where = where.CheckNullAnd(x => x.PartMan.Contains(partMan), partMan);
                where = where.CheckNullAnd(x => x.CheckDate > checkdatestart, checkdatestart);
                where = where.CheckNullAnd(x => x.CheckDate <= checkdateend, checkdateend);

                var query = _dbContext.Rss_Check.AsQueryable();

                query = query.Where(where.Expand()).OrderByDescending(x => x.Id);

                var list = query.Paged(pageindex, pagesize).ToList();
                var totalCount = query.Count();
                var data = list.Select(_mapper.Map<Rss_Check, Rss_Check_ViewModel>);
                response.SetData(data, totalCount);
                return response;
            }
        }

        /// <summary>
        /// 现场监管----开始检查 修改状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]

        public ResponseModel RSSStartState([Required] int id)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    var res = _dbContext.Rss_Check.Where(x => x.Id == id)
                        .SetField(x => x.State).WithValue("检查中")
                        .SetField(x => x.ModifiedOn).WithValue(DateTime.Now)
                        .SetField(x => x.ModifiedBy).WithValue("系统")
                        .Update();
                    if (res > 0)
                        response.SetSuccess("操作成功");
                    else
                        response.SetFailed("操作失败");

                }

            }
            catch (Exception ex)
            {
                response.SetFailed("操作失败");
                response.Data = ex.Message;
            }
            return response;
        }
        /// <summary>
        /// 现场监管----审批 修改状态
        /// </summary>
        /// <param name="id">现场监管唯一编号</param>
        /// <param name="YesNo">通过true；未通过fales</param>
        /// <param name="nopasscontent">未通过原因</param>
        /// <returns></returns>
        [HttpPost]

        public ResponseModel RSSPassState([Required] int id, [Required] bool YesNo, [Required] string nopasscontent)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    var res = -1;
                    if (YesNo)
                    {
                        res = _dbContext.Rss_Check.Where(x => x.Id == id)
                            .SetField(x => x.State).WithValue("审批通过")
                            .SetField(x => x.ModifiedOn).WithValue(DateTime.Now)
                            .SetField(x => x.ModifiedBy).WithValue("系统")
                            .Update();
                    }
                    else {
                        res = _dbContext.Rss_Check.Where(x => x.Id == id)
                                .SetField(x => x.State).WithValue("审批未通过")
                                .SetField(x => x.NoPassContent).WithValue(nopasscontent)
                                .SetField(x => x.ModifiedOn).WithValue(DateTime.Now)
                                .SetField(x => x.ModifiedBy).WithValue("系统")
                                .Update();
                    }
                    if (res > 0)
                        response.SetSuccess("操作成功");
                    else
                        response.SetFailed("操作失败");

                }

            }
            catch (Exception ex)
            {
                response.SetFailed("操作失败");
                response.Data = ex.Message;
            }
            return response;
        }
        #endregion
        #region 检查纪要、建议
        /// <summary>
        /// 现场监管----检查纪要 添加 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]

        public ResponseModel RSSCheckSummary([FromBody] Rss_Check_ViewModel model)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    var entity = _mapper.Map<Rss_Check_ViewModel, Rss_Check>(model);
                    var entryEntity = _dbContext.Rss_Check.Attach(entity);
                    if (entity.Id > 0)
                    {
                        var editentity = _dbContext.Rss_Check.AsNoTracking().Where(x => x.Id == entity.Id).AsNoTracking().FirstOrDefault();
                        if (editentity == null)
                        {
                            response.SetFailed("无法修改，数据不存在请刷新页面");
                            return response;
                        }
                        //要修改的类型
                        _dbContext.ModifyEntityValue(entity, x => new
                        {
                            x.CheckSummary,
                            x.CheckSummaryFile
                        });
                        entity.State = "待审核";
                        entity.ModifiedBy = "系统";
                        entity.ModifiedOn = System.DateTime.Now;
                    }
                    _dbContext.SaveChanges();
                    response.SetSuccess("操作成功");

                }
            }
            catch (Exception ex)
            {
                response.SetFailed("操作失败");
                response.Data = ex.Message;
            }
            return response;
        }
        /// <summary>
        /// 现场监管----建议 添加 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel RSSCheckissure([FromBody] Rss_Checkissure_ViewModel model)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    var entity = _mapper.Map<Rss_Checkissure_ViewModel, Rss_Checkissure>(model);
                    var entryEntity = _dbContext.Rss_Checkissure.Attach(entity);
                    if (entity.Id > 0)
                    {
                        var editentity = _dbContext.Rss_Checkissure.AsNoTracking().Where(x => x.Id == entity.Id && x.Deleted == false).AsNoTracking().FirstOrDefault();
                        if (editentity == null)
                        {
                            response.SetFailed("无法修改，数据不存在请刷新页面");
                            return response;
                        }
                        entryEntity.State = EntityState.Modified;
                        entryEntity.Property(p => p.CreatedOn).IsModified = false;
                        entryEntity.Property(p => p.CreatedBy).IsModified = false;
                        entryEntity.Property(p => p.Deleted).IsModified = false;
                        entity.ModifiedBy = "系统";
                        entity.ModifiedOn = System.DateTime.Now;
                    }
                    else
                    {
                        entryEntity.Property(p => p.ModifiedBy).IsModified = false;
                        entryEntity.Property(p => p.ModifiedOn).IsModified = false;
                        entity.Deleted = false;
                        entity.CreatedBy = "系统";
                        entity.CreatedOn = System.DateTime.Now;

                    }
                    _dbContext.SaveChanges();
                    response.SetSuccess("操作成功");

                }
            }
            catch (Exception ex)
            {
                response.SetFailed("操作失败");
                response.Data = ex.Message;
            }
            return response;
        }
        /// <summary>
        /// 现场监管----建议 删除
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel RSSCheckissureDelete([Required] int id)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    var res = _dbContext.Rss_Checkissure.Where(x => x.Id == id)
                        .SetField(x => x.Deleted).WithValue(true)
                        .SetField(x => x.ModifiedOn).WithValue(DateTime.Now)
                        .SetField(x => x.ModifiedBy).WithValue("系统")
                        .Update();
                    if (res > 0)
                        response.SetSuccess("删除成功");
                    else
                        response.SetFailed("删除失败");

                }

            }
            catch (Exception ex)
            {
                response.SetFailed("删除失败");
                response.Data = ex.Message;
            }
            return response;
        }
        /// <summary>
        /// 现场监管----建议   详情
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseModel<Rss_Checkissure_ViewModel> RSSCheckissureDetail([Required] int id)
        {
            using (_dbContext)
            {
                var response = new ResponseModel<Rss_Checkissure_ViewModel>();
                var query = _dbContext.Rss_Checkissure.AsNoTracking().Where(x => x.Id == id && x.Deleted == false).FirstOrDefault();
                var data = _mapper.Map<Rss_Checkissure, Rss_Checkissure_ViewModel>(query);
                response.SetData(data);
                return response;
            }

        }
        /// <summary>
        /// 现场监管----建议  查询
        /// </summary>
        /// <param name="checkid">现场监管唯一编号</param>
        /// <param name="checkno">现场监管检查编号(规则生成)</param>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">显示条数</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseResultModel<IEnumerable<Rss_Checkissure_ViewModel>> RSSCheckissureSearch(int? checkid, string checkno, int pageindex = 1, int pagesize = 10)
        {
            using (_dbContext)
            {
                var response = ResponseModelFactory<IEnumerable<Rss_Checkissure_ViewModel>>.CreateResultInstance;
                Expression<Func<Rss_Checkissure, bool>> where = p => true;

                where = where.CheckNullAnd(x => x.CheckId == checkid, checkid);

                where = where.CheckNullAnd(x => x.CheckNo == checkno, checkno);
                where = where.And(x => x.Deleted == false);
                var query = _dbContext.Rss_Checkissure.AsQueryable();

                query = query.Where(where.Expand()).OrderByDescending(x => x.Id);

                var list = query.Paged(pageindex, pagesize).ToList();
                var totalCount = query.Count();
                var data = list.Select(_mapper.Map<Rss_Checkissure, Rss_Checkissure_ViewModel>);
                response.SetData(data, totalCount);
                return response;
            }

        }
        #endregion
    }
}
